
export class SpriteUtil
{
    private constructor(){};
    private static p_mSpriteUtil: SpriteUtil = null;
    static getInstance(): SpriteUtil
    {
        if(this.p_mSpriteUtil == null || this.p_mSpriteUtil == void 0){
            this.p_mSpriteUtil = new SpriteUtil;
        }
        return this.p_mSpriteUtil;
    }
    //最多加载次数
    private maxTime: number = 3;
    //第几次加载
    private usingId = {};
    /**
     * 
     * @param sprUrl 图片地址
     * @param sprite 节点的精灵组件
     * @param callback 回调函数
     * @param args 回调参数
     */
    changeCCNodeSpriteFrame(sprUrl: string = '', sprite: cc.Sprite, callback: Function = ()=>{}, ...args)
    {
        var self = this;
        if(sprUrl == '' || sprite == null || sprite == void 0)return;
        var sprRes: cc.SpriteFrame = cc.loader.getRes(sprUrl, cc.SpriteFrame);
        if(sprRes)
        {
            sprite.spriteFrame = sprRes;
            callback && callback(...args);
        }
        else
        {
            cc.loader.loadRes(sprUrl, cc.SpriteFrame, function(err, spriteFrame)
            {
                if(err)
                {
                    if(self.usingId[sprUrl] == null || self.usingId[sprUrl] == void 0)
                    {
                        self.usingId[sprUrl] = 1;
                    }
                    else
                    {
                        ++self.usingId[sprUrl];
                    }
                    if(self.usingId[sprUrl] < self.maxTime)
                    {
                        self.changeCCNodeSpriteFrame(sprUrl, sprite, callback, ...args);
                        console.warn(`路径为 ${sprUrl} 的图片加载失败, 次数: ${self.usingId[sprUrl]}`);
                    }
                    else
                    {
                        console.warn(`路径为 ${sprUrl} 的图片加载失败, 请检查路径`);
                    }
                }
                else
                {
                    sprite.spriteFrame = spriteFrame;
                    callback && callback(...args);
                    if(self.usingId[sprUrl] != null && self.usingId[sprUrl] != void 0)
                    {
                        delete self.usingId[sprUrl];
                    }
                }
            });
        }
    }
}